/**
 *
 */
module.exports = function(RED) {
	var jsonFile = require('jsonfile')
    var os = require("os");
    function configManager(n) {
        RED.nodes.createNode(this,n);
        var node = this;
        var customconfigs = n.configs || [];
        var defualtconfigs = [{cn:"relayinitinfo",cp:"/node-red/gw/config/relayinitinfo.json"},{cn:"message",cp:"/node-red/gw/config/message.json"},{cn:"ecoserver",cp:"/node-red/gw/config/ecoserver.json"},{cn:"controller",cp:"/node-red/gw/config/controller.json"}];
        var globalContext = this.context().global;
        var initConfig = function(configs) {
          for (var i=0; i< configs.length; i+=1) {
            var config = configs[i];
            var configNm = config.cn || "";
            var filepath = config.cp || "";

            if (configNm == "") {
                node.warn("[Loader Config Failed] Config Name Empty");
                throw new Error("[Loader Config Failed] Config Name Empty");
            } else if (filepath === "") {
                node.warn("[Loader Config Failed] File Path Empty");
                throw new Error("[Loader Config Failed] Config Name Empty");
            } else {
              try{
                  var data = jsonFile.readFileSync(config.cp);
                  if (data && data != "") {
                    globalContext.set(configNm, data);
                  } else {
                    node.error("[Loader Config Failed] Data Not Exist:"  + config.cp);
                    throw new Error("[Loader Config Failed] Data Not Exist:"  + config.cp);
                  }
              } catch(e){
                node.error("[Loader Config Failed] No Such File:"  + config.cp + " " + e.message);
                throw e;
              }
            }

              node.log("[Loaded Config Successlly] Name:" + configNm + ", Path:"+ filepath);
          }
        }
        initConfig(defualtconfigs);
        initConfig(customconfigs);
    }
    RED.nodes.registerType("config-manager",configManager);
}